package com.rpframework.website.device.act.api;

import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.rpframework.core.BaseAct;
import com.rpframework.core.utils.DictionarySettingUtils;
import com.rpframework.core.utils.MessageFormatter;
import com.rpframework.core.utils.SpringUtils;
import com.rpframework.core.utils.TagUtils;
import com.rpframework.module.common.service.SMSService;
import com.rpframework.utils.AlgorithmEnum;
import com.rpframework.utils.AlgorithmUtils;
import com.rpframework.utils.GenerateUtils;
import com.rpframework.utils.NumberUtils;
import com.rpframework.utils.Pager;
import com.rpframework.website.device.dao.IConvertDao;
import com.rpframework.website.device.dao.IGuideDao;
import com.rpframework.website.device.dao.IInteractDao;
import com.rpframework.website.device.dao.IPraiseDao;
import com.rpframework.website.device.dao.ITCommentDao;
import com.rpframework.website.device.domain.Guide;
import com.rpframework.website.device.domain.User;
import com.rpframework.website.device.exception.APICodeException;
import com.rpframework.website.device.service.GuideService;
import com.rpframework.website.device.service.IConvertService;
import com.rpframework.website.device.service.UnitService;
import com.rpframework.website.device.service.UserService;
import com.rpframework.website.device.util.HConfig;
import com.rpframework.website.device.util.HConstants;

@Controller
@RequestMapping("/api2")
public class ApiUserAct2 extends BaseAct {
	@Resource UserService userService;
	@Resource SMSService smsService;
	@Resource GuideService guideservice;
	@Resource UnitService unitService;
	@Resource IConvertService ConvertService;
	
	public @Resource IGuideDao iDao;
	public @Resource ITCommentDao iCommentDao;
	public @Resource IInteractDao iInteractDao;
	public @Resource IPraiseDao iPraiseDao;
	public @Resource IConvertDao iConvertDao;
	Gson gson =new Gson();
	//登录
	@RequestMapping("/login")
	public @ResponseBody String login(@RequestParam(required=false) String tel, 
			@RequestParam(required=false) String password, 
			HttpSession session, 
			HttpServletRequest request, HttpServletResponse response,
			@RequestParam(value = "callback",required = false ) String callback){
		if(StringUtils.isBlank(tel) || StringUtils.isBlank(password)) {
			throw new APICodeException(-5, "非法参数!");
		}
		
		User user = userService.findUserByContact(tel);
		if(user == null) {
			throw new APICodeException(-2, "用户名不存在!");
		}
		
		password = AlgorithmUtils.encodePassword(password, AlgorithmEnum.MD5) ;
		if (!StringUtils.equals(password, user.getPassword())) {
			throw new APICodeException(-3, "密码错误!");
		}
		
		if (user.getState() != 1) {
			throw new APICodeException(-4, "您的帐户不是启用状态！");
		}
		
		userService.doLoginRecord(user, request);
		
		session.setAttribute(SESSION_USER_KEY, user);
		//用户Id + 加密tokenKey + 加密时间 加密成一条密钥存在cookie里，在 EDongWangApi 连接器里坐未登录的情况下是否自动登陆
		HConfig examConfig = SpringUtils.getBean(HConfig.class);
		JsonObject tokenJson = new JsonObject();
		tokenJson.addProperty("id", user.getId());
		tokenJson.addProperty("ct", System.currentTimeMillis()/1000);
		tokenJson.addProperty("tk", examConfig.tokenkey);
		
		String loginEncrypt = AlgorithmUtils.enBase64(tokenJson.toString());
		Cookie cookie = new Cookie(HConstants.COOKIE_LOGIN_ENCRYPT_KEY, loginEncrypt);
		response.addCookie(cookie);
		
		JsonObject json = new JsonObject();
		json.addProperty("succ", true);
		json.addProperty("msg", "Login success");
		json.addProperty("userId", user.getId());
		if(StringUtils.isNotBlank(callback))return (callback + "(" + json + ")");
		return ""+json ;
	}
	
	
		//给指定手机号 发送验证码   tel(手机号)
		@RequestMapping("/sendsms_for_code")
		public @ResponseBody JsonElement sendSMSForForget(
				@RequestParam(required=false) String tel,
				@RequestParam(required=false) Integer type,//1注册  2重置密码 
				HttpSession session, HttpServletRequest request) {
			if(StringUtils.isEmpty(tel)) {
				throw new APICodeException(-1, "非法参数!");
			}
			
			String verifyCode = String.valueOf(NumberUtils.random(6));
			String sendContent = DictionarySettingUtils.getParameterValue("sendsms.forget");
			if(StringUtils.isBlank(sendContent)) {
				sendContent =  "本次注册验证码:{}，请牢记";
			}
			sendContent = MessageFormatter.format(sendContent, verifyCode);
			
			boolean flag = smsService.sendSMS(type, tel, verifyCode, sendContent);
			if(!flag) {
				throw new APICodeException(-2, "短信发送失败!");
			}
			JsonObject json = new JsonObject();
			json.addProperty("succ", true);
			return json;
		}
		//注册 或修改密码
		@RequestMapping("/submit")
		public @ResponseBody JsonElement regist(HttpSession session, HttpServletRequest request) {
			String tel = request.getParameter("tel");
			String type = request.getParameter("type");//1注册  2重置密码 
			String password = request.getParameter("password");
			String verifyCode = request.getParameter("code");
			
			if(StringUtils.isBlank(tel)
					||StringUtils.isBlank(password)
					||StringUtils.isBlank(type)
					||StringUtils.isBlank(verifyCode)) {
				throw new APICodeException(-1, "非法参数!");
			}
			if(!smsService.checkVerifyCode(Integer.valueOf(type), tel, verifyCode)) {
				throw new APICodeException(-4, "验证码不正确!");
			}
			
			User user = userService.findUserByContact(tel);
			if(user != null && "1".equals(type)) {
				throw new APICodeException(-2, "存在的手机号!");
			}
			boolean flag =false;
			String passwordhx = password;
			password = AlgorithmUtils.encodePassword(password, AlgorithmEnum.MD5);
			if(user == null && "1".equals(type)) {
				user = new User();
				user.setTel(tel);
				user.setUserName(tel);
				user.setNickName("昵称");
				user.setHeadImg("/device/interact/20160724161730254753.png");//默认头像
				user.setRealName("");
				user.setDbNo(GenerateUtils.generateCharAndNumr(7));
				user.setState(1);//默认禁用 等地址添加成功后再更改
				user.setSex(2);//默认女
				user.setCreateTime(System.currentTimeMillis() / 1000);
				user.setReadTime(System.currentTimeMillis()/1000); //重置当前时间    用于判断是否有未读消息
				user.setPassword(password);
				userService.insert(user);
			}else{
				user.setPassword(password);
				userService.update(user);
			}
			smsService.setVerifyCodeVaild(HConstants.ChannelType.SEND_SMS_REGIST_CHANNEL_TYPE, tel);
			session.removeAttribute(SESSION_USER_KEY);
			JsonObject json = new JsonObject();
			json.addProperty("succ", true);
			return json;
		}
		
		/**
		 *   我的     修改密码		
		 */
		@RequestMapping(value="/change_pwd" ,produces = "application/json; charset=utf-8")
		public @ResponseBody String changePwd(
				@RequestParam(required=false) String oldPassWord ,
				@RequestParam(required=false) String nPassWord ,
				@RequestParam(required=false) String qPassWord , 
				@RequestParam(value = "callback",required = false ) String callback,
				HttpSession session){
			JsonObject json = new JsonObject();
			User user = getSessionUser(session);
			if( user == null ){
				throw new APICodeException(-4, "你还没登陆!");
			}
			oldPassWord = AlgorithmUtils.encodePassword(oldPassWord, AlgorithmEnum.MD5);
			if(!oldPassWord.equals(user.getPassword())){
				throw new APICodeException(-1, "原密码错误!");
			}
			if(StringUtils.isBlank(nPassWord)){
				throw new APICodeException(-2, "新密码不能为空!");
			}
			if(!nPassWord.equals(qPassWord)){
				throw new APICodeException(-3, "两次密码不一致!");
			}
			String nPwd = AlgorithmUtils.encodePassword(nPassWord, AlgorithmEnum.MD5);
			user.setPassword(nPwd);
			boolean flag = userService.update(user);
			if(flag){
				json.addProperty("succ", true);
			} else {
				json.addProperty("succ", false);
			}	
			return (callback + "(" + json + ")");
		}
		
		/**
		 * 修改手机号
		 * @time 2015年8月10日 上午9:30:39
		 */
		@RequestMapping(value="/sendsms_modify_tel" , produces = "application/json; charset=utf-8")
		public @ResponseBody String sendSms_Modify_Tel(
				@RequestParam(value = "callback",required = false ) String callback,
				@RequestParam(value = "newTel",required = false ) String newTel,
				HttpSession session) {
			String verifyCode = String.valueOf(NumberUtils.random(6));
			String sendContent = DictionarySettingUtils.getParameterValue("sendsms.forget_passowrd");
			if(StringUtils.isBlank(sendContent)) {
				sendContent =  "本次修改手机号验证码:{}，请牢记";
			}
			sendContent = MessageFormatter.format(sendContent, verifyCode);
			boolean flag = smsService.sendSMS(3, newTel, verifyCode, sendContent);//直接给新手机号发验证码
			JsonObject json = new JsonObject();
			String msg = "修改手机号发送验证码";
			json =  isSuccessJson(flag,msg);
			if(StringUtils.isNotBlank(callback))return (callback + "(" + json + ")");
			return ""+json ;
		}
		/**
		 * 操作结果为boolean类型的返回方法
		 * @param flag
		 * @param msg
		 * @return
		 */
		public JsonObject isSuccessJson(boolean flag, String msg) {
			JsonObject json = new JsonObject();
			Integer code = 500;
			if(flag)code =200;
			json.addProperty("code", code);
			json.addProperty("msg", msg+flag);
			return json ;
		}

		/**
		 * 修改手机号
		 * @param session
		 * @param request
		 * @param attr
		 * @return
		 */
		@RequestMapping("/modify_tel")
		public @ResponseBody String Modify_Tel(HttpSession session, 
				@RequestParam(value = "callback",required = false ) String callback,
				HttpServletRequest request,RedirectAttributes attr) {
			// 获得请求参数值
			User sessionUser = (User) session.getAttribute(SESSION_USER_KEY);
			String tel = request.getParameter("tel");
			String code = request.getParameter("code");
			JsonObject json = new JsonObject();
			if(StringUtils.isBlank(tel) ||StringUtils.isBlank(code)) {
				throw new APICodeException(-1, "参数错误！");
			}
			if(!smsService.checkVerifyCode(3, tel, code)) {
				throw new APICodeException(-1, "验证码错误!");
			}
			User user = userService.findUserByContact(tel);
			User dbuser = userService.findUserByContact(sessionUser.getTel());
			if(user != null) {
				throw new APICodeException(-1, "手机号存在!");
			}
			dbuser.setTel(tel);
			dbuser.setModifyTime(System.currentTimeMillis()/1000);
			boolean flag = userService.update(dbuser);
			if(flag){
				json.addProperty("succ", true);
				json.addProperty("msg", "更改成功");
			}else{
				json.addProperty("succ", false);
				json.addProperty("msg", "更改失败");
			}
			if(StringUtils.isNotBlank(callback))return (callback + "(" + json + ")");
			return ""+json ;
		}
		
		/**
		 * 用户退出
		 */
		@RequestMapping("remove_session_user")
		public @ResponseBody String removeSessionUser(HttpSession session,
				@RequestParam(value = "callback",required = false ) String callback
				){
			JsonObject json = new JsonObject();
			
			User currUser = getSessionUser(session);
			if(currUser != null){
				session.removeAttribute(SESSION_USER_KEY);
			}
			json.addProperty("succ", true);
			return (callback + "(" + json + ")");
		}
		/* 修改个人资料   */
		
		@RequestMapping(value="/update",produces = "application/json; charset=utf-8")
		public @ResponseBody String updateData(
				@RequestParam(value="sex",required = false ) Integer sex,//页面请求参数性别
				@RequestParam(value="nickName",required = false ) String nickName,//昵称
				@RequestParam(value="headImg",required = false ) String headImg,//头像地址
				@RequestParam(value="constellation",required = false ) String constellation,//修改出生时间
				@RequestParam(value = "callback",required = false ) String callback,
				HttpSession session){
			User sessionuser=getSessionUser(session);
			JsonObject json = new JsonObject();
			if(sessionuser==null){
				 json.addProperty("code", -100);
				return ""+json ;
				//throw new APICodeException(-4, "你还没登陆!");
			}
			User user = userService.select(sessionuser.getId());//根据id查询用户返回用户信息
			if(NumberUtils.isValid(sex))user.setSex(sex);//修改用户性别
			if(StringUtils.isNotBlank(nickName))user.setNickName(nickName);//修改昵称
			if(StringUtils.isNotBlank(headImg))user.setHeadImg(headImg);//修改头像
			if(StringUtils.isNotBlank(constellation))user.setConstellation(constellation);//修改出生时间
			boolean  b = userService.update(user);//将用户资料提交到数据库
			if(b)json.addProperty("code", 200); else json.addProperty("code", 500);
			
			json.addProperty("nickName",user.getNickName());
			json.addProperty("tel",user.getTel());
			json.addProperty("sex",user.getSex());//性别
			json.addProperty("headImg", TagUtils.getFileFullPath(user.getHeadImg()));
			json.addProperty("constellation",user.getConstellation());
			if(StringUtils.isNotBlank(callback))return (callback + "(" + json + ")");
				return ""+json ;
		}	
		

		/**
		 * 我的  消息中心
		 */
	
		@RequestMapping(value="/list",produces = "application/json; charset=utf-8")
		public @ResponseBody String list(@RequestParam(value="pager", required=false)Pager<Guide> pager, Map<Object, Object> model,
				@RequestParam(value = "id",required = false ) String id,
				@RequestParam(value = "callback",required = false ) String callback,
				HttpSession session){
			if(pager==null){
				pager=new Pager<Guide>();
			}
			User sessionuser=getSessionUser(session);
			if(sessionuser==null){
				throw new APICodeException(-4, "你还没登陆!");
			}
			pager.getSearchMap().put("propertyid", String.valueOf(sessionuser.getEstateId()));
			pager.getSearchMap().put("typeid", String.valueOf(2));
			pager=guideservice.getpager(pager);
			List<Guide> list = iDao.doPraiseByGuide(sessionuser.getLastLoginTime());
			Integer size = iDao.GuideSize(sessionuser.getLastLoginTime());
			//List<Guide> list=pager.getItemList();
			JsonObject json=new JsonObject();
			json.addProperty("size", size);
			JsonArray array=new JsonArray();
			json.add("arrays", array);
			for (Guide act : list) {
				JsonObject jsonObj = gson.toJsonTree(act).getAsJsonObject();
				jsonObj.addProperty("sytime", TagUtils.formatDate(act.getStarttime()));
				array.add(jsonObj);
			}
			if(StringUtils.isNotBlank(callback))return (callback + "(" + json + ")");
			return ""+json ;
		}

		/* click 重置消息 提示时间 */
		
		
		@RequestMapping(value="/click",produces = "application/json; charset=utf-8")
		public @ResponseBody String updateData1(
				@RequestParam(value = "callback",required = false ) String callback,
				HttpSession session){
			User sessionuser=getSessionUser(session);
			if(sessionuser==null)throw new APICodeException(-4, "你还没登陆!");
			User user = userService.select(sessionuser.getId());//根据id查询用户返回用户信息
			user.setReadTime(System.currentTimeMillis()/1000); //重置当前时间    用于判断是否有未读消息
			boolean  b = userService.update(user);//将用户资料提交到数据库
			JsonObject json = new JsonObject();
			if(b)json.addProperty("code", 200); else json.addProperty("code", 500);
			
			if(StringUtils.isNotBlank(callback))return (callback + "(" + json + ")");
				return ""+json ;
		}	
		
		/**
		 * 消息中心  根据id查询
		 * @param windesid
		 * @param callback
		 * @param model
		 * @param session
		 * @return
		 */
		@RequestMapping(value="/listwinedstole",produces = "application/json; charset=utf-8")
		public @ResponseBody String listwineds(@RequestParam String windesid,
			@RequestParam(value = "callback",required = false ) String callback,
				Map<Object, Object> model,
				HttpSession session){
			Guide wind=guideservice.selectOnlyOne(Integer.parseInt(windesid));
			JsonObject json=new JsonObject();
			json.addProperty("sytitle", wind.getTitle());
			json.addProperty("sycontent", wind.getMsg());
			json.addProperty("username", wind.getUsername());
			
			json.addProperty("sytime", TagUtils.formatDate(wind.getStarttime()));
			if(StringUtils.isNotBlank(callback))return (callback + "(" + json + ")");
			return ""+json ;
		}
		
//		/**
//		 * 查询 我的 评论   我的发布  我的收藏 我的点赞  相关数量  用于积分增量
//		 */
//		@RequestMapping(value="/integral",produces = "application/json; charset=utf-8")
//		public @ResponseBody String integral(@RequestParam(value="pager", required=false)Pager<Unit> pager, Map<Object, Object> model,
//				@RequestParam(value = "callback",required = false ) String callback,
//				HttpSession session){
//			User sessionuser=getSessionUser(session);
//			if(sessionuser==null){
//				throw new APICodeException(-4, "你还没登陆!");
//			}
//			Integer size = iCommentDao.queryIntegral(sessionuser.getId());//查询我是否可以评论，获取积分
//			Integer size1 = iInteractDao.queryIntegral(sessionuser.getId());//查询我是否可以发布，获取积分
//			Integer size2 = iPraiseDao.queryIntegral(sessionuser.getId(),2);//查询我是否可以收藏，获取积分
//			Integer size3 = iPraiseDao.queryIntegral(sessionuser.getId(),3);//查询我是否可以点赞，获取积分
//			Unit unit = unitService.select(1);//根据id查询用户返回用户信息
//			JsonObject json=new JsonObject();
//			json.addProperty("pinglunjifen", size*unit.getPL());
//			json.addProperty("fabujifen", size1*unit.getFB());
//			json.addProperty("shoucangjifen", size2*unit.getSC());
//			json.addProperty("dianzanjifen", size3*unit.getDZ());
//			
//
//			if(StringUtils.isNotBlank(callback))return (callback + "(" + json + ")");
//			return ""+json ;
//		}
		
}
